#include "quantitydelegate.h"

#include <QSpinBox>

#include <QStyleOptionViewItem>
#include <QAbstractItemModel>
#include <QModelIndex>


QuantityDelegate::QuantityDelegate(QObject *parent)
:   QStyledItemDelegate(parent)
{
}

QWidget *QuantityDelegate::createEditor(
    QWidget *parent
,   const QStyleOptionViewItem &item
,   const QModelIndex &) const
{
    QSpinBox *editor = new QSpinBox(parent);

    editor->setPrefix("    [ ");
    editor->setSuffix(" ]    ");

    editor->setMaximum(99999999);
    editor->setMinimum(0);

    editor->setAlignment(item.displayAlignment);

    return editor;
}

void QuantityDelegate::setEditorData(
    QWidget *editor
,   const QModelIndex &index) const
{
    int value = index.model()->data(index, dataRole()).toInt();

    QSpinBox *spinBox = dynamic_cast<QSpinBox*>(editor);
    spinBox->setValue(value);
    spinBox->setAlignment(Qt::AlignRight);
}

void QuantityDelegate::setModelData(
    QWidget *editor
,   QAbstractItemModel *model
,   const QModelIndex &index) const
{
    QSpinBox *spinBox = dynamic_cast<QSpinBox*>(editor);

    spinBox->interpretText();
    int value = spinBox->value();

    model->setData(index, value, QuantityDelegate::dataRole());
    model->setData(index, textFromValue(value), Qt::EditRole);
}

void QuantityDelegate::updateEditorGeometry(
    QWidget *editor
,   const QStyleOptionViewItem &option
,   const QModelIndex &) const
{
    editor->setGeometry(option.rect);
}

const QString QuantityDelegate::textFromValue(uint value)
{
    return QString("    [ %1 ]    ").arg(value);
}

const int QuantityDelegate::dataRole()
{
    return Qt::UserRole + 1;
}
